﻿using EasyModbus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zhy.EasyModbusTCP
{
    internal class MyModbusTCP
    {
        private static readonly MyModbusTCP instance = new MyModbusTCP();

        /// <summary>
        /// 私有构造函数，防止外部实例化
        /// </summary>
        private MyModbusTCP() { }

        /// <summary>
        /// 提供一个全局访问点
        /// </summary>
        public static MyModbusTCP Instance => instance;

        /// <summary>
        /// Modbus客户端实例
        /// </summary>
        ModbusClient modbusClient;
        /// <summary>
        /// Modbus TCP 服务器地址
        /// </summary>
        string ipAddress = "127.0.0.1"; // 修改为你的 Modbus TCP 服务器的 IP 地址
        /// <summary>
        /// Modbus TCP 的默认端口是 502
        /// </summary>
        int port = 502; // 
        /// <summary>
        /// Modbus 设备单元标识符，根据你的设备设置
        /// </summary>
        byte unitIdentifier = 1; // 

        /// <summary>
        /// 链接客户端
        /// </summary>
        public void Connect()
        {
            // 创建 Modbus TCP 客户端实例
            modbusClient = new ModbusClient(ipAddress, port);
            modbusClient.UnitIdentifier = unitIdentifier;
            modbusClient.Connect(); // 连接到 Modbus TCP 服务器
        }

        /// <summary>
        /// 断开链接
        /// </summary>
        public void Disconnect() 
        {
            modbusClient.Disconnect(); // 断开连接
        }

        /// <summary>
        /// 读取保持寄存器
        /// </summary>
        /// <param name="startAddress"></param>
        /// <param name="numberOfRegisters"></param>
        /// <returns></returns>
        public int[] ReadHoldingRegisters(int startAddress, int numberOfRegisters)
        {
            try
            {
                // 从保持寄存器读取数据，例如读取地址为 startAddress 的寄存器值，寄存器数量为 numberOfRegisters
                int[] registers = modbusClient.ReadHoldingRegisters(startAddress, numberOfRegisters);
                return registers;
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取寄存器时发生错误: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 写入保持寄存器
        /// </summary>
        public void WriteHoldingRegister()
        {
            try
            {
                // 向保持寄存器（例如，地址为1的寄存器）写入值
                modbusClient.WriteSingleRegister(1, 1234); // 将地址为1的寄存器的值设置为1234
                Console.WriteLine("Register written successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error writing register: {ex.Message}");
            }
        }

    }
}
